package hh.compile;

import hh.util.CommonUtil;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.util.Arrays;
import java.util.List;

/**
 * @author huanghuai
 * @date 2020/9/27
 */
public class CompileUtil2 {

    private volatile List<String> options = CommonUtil.newArrayList(
            "-source", "1.8",
            "-source", "1.8",
            "-source", "1.8",
            "-source", "1.8",
            "-source", "1.8",
            "-source", "1.8"
    );

    public static Class compile(String fullClassName, String code) {
        //文件路径
        String fullQuanlifiedFileName = "D:\\Client.java";


        //获取编译器
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();


        //获取文件管理器 参数依次为错误监听器，区域对象，编码
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);


        //通过文件全路径获取要编译的文件对象
        Iterable<? extends JavaFileObject> files = fileManager.getJavaFileObjectsFromStrings(Arrays.asList(fullQuanlifiedFileName));


        //创建编译任务 参数为错误输出流，文件管理器，错误处理器，编译器选项，参与编译的class，带编译的java文件
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, files);


        //执行任务
        Boolean result = task.call();
        if (result) {
            System.out.println("Succeeded");
        }
        return null;
    }

}
